// 上传图片

<template>
  <div class="upload-file-box">
    <el-upload
      class="upload-demo"
      :action="uploadApi"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-remove="beforeRemove"
      :before-upload="handleBeforeUpload"
      multiple
      :limit="countLimit"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">
        当出现绿色勾选时上传成功，点击可查看视频详情
      </div>
    </el-upload>
  </div>
</template>

<script>
import jhTools from "@/utils/jhTools"; //工具函数
import API from "@/utils/api_config.js"; //引入api

export default {
  components: {},
  props: {
    countLimit: {
      type: Number,
    },
    fileListProp: {
      type: String,
    },
    isNecessary: {
      type: String,
    },
    uploadApi: {
      type: String,
      default: API.common.upload,
    },
  },
  data() {
    return {
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url:
        //     "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
    };
  },
  mounted() {
    if (this.fileListProp) {
      var defaultFileListArr = this.fileListProp.split(";");
      var trueFileListArr = [];
      var fileName = "";
      var uid = "";
      defaultFileListArr.forEach((item, index) => {
        // console.log(item);
        item.replace(/&fileName=(.*?)&/, (node, $1) => {
          fileName = $1;
        });
        item.replace(/&uid=(\d.*)/, (node, $1) => {
          uid = $1;
        });
        trueFileListArr.push({
          name: fileName,
          uid: uid,
          url: item,
        });
      });
      this.fileList = trueFileListArr;
    }
  },
  methods: {
    //移除文件的钩子
    handleRemove(file, fileList) {
      // console.log(file, fileList); //上传会走移除的钩子
      console.log("移除");
      this.fileList = fileList;
      //回传
      var fileDataStr = this.handleArrayToString(this.fileList);
      this.$emit("uploadSuccess", fileDataStr);
    },

    //点击已上传文件的钩子 点击的钩子
    handlePreview(file) {
      // window.location.href = file.url;
      var tempwindow = window.open("_blank");
      tempwindow.location = file.url;
    },

    //超出文件个数的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传${this.countLimit}个文件`);
    },

    //确认移除文件时的钩子，返回false则不删除
    beforeRemove(file, fileList) {
      //新增的情况
      if(fileList.length > this.fileList.length) {
        return false;
      }
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    //上传文件前的钩子
    handleBeforeUpload(file) {
      this.handleUpladFiles(file); //上传文件
      return false; //不上传文件
    },

    //上传
    handleUpladFiles(file) {
      console.log("上传的文件", file);
      var url = API.common.upload;
      let formdata = new FormData();
      formdata.append("file", file);
      // var imgs = {
      //   uid: file.uid,
      //   name: "",
      //   url: "",
      // };
      var _this = this;
      var fileItem = {
        name: file.name,
        uid: file.uid,
      };
      jhTools.post(
        url,
        formdata,
        null,
        (res) => {
          if (res.code == 200) {
            console.log("上传成功", res.data.fullUrl);
            fileItem.url = res.data.fullUrl;
            //组合
            var completeUrl =
              res.data.fullUrl +
              "&fileName=" +
              fileItem.name +
              "&uid=" +
              fileItem.uid;
            //添加
            _this.fileList.push(fileItem);
            console.log("长度", _this.fileList.length);
            //回传
            var fileDataStr = _this.handleArrayToString(_this.fileList);
            _this.$emit("uploadSuccess", fileDataStr);

            var limitCount = this.countLimit ? +this.countLimit : 1;
            if (this.fileList.length <= limitCount) {
              //提示限制
              this.$message({
                type: "success",
                message: `上传成功！还可上传${
                  limitCount - this.fileList.length
                }张`,
              });
            }

            // imgs.name = res.data.fullUrl;
            // imgs.url = res.data.fullUrl;

            // this.imgArr.push(imgs);
            // this.fileShowList = this.imgArr;
          }
        },
        (err) => {
          this.$message({
            type: "warning",
            message: "上传未成功"
          });
          this.$set(this.fileList, this.fileList); //更新
        }
      );
    },

    //上传成功
    handleSuccess(res, file, fileList) {
      console.log("自动上传结果", res);
    },

    //数组转字符串
    handleArrayToString(arr) {
      var str = "";
      arr.forEach((item, index) => {
        str += item.url + "&fileName=" + item.name + "&uid=" + item.uid;
        if (index != arr.length - 1) {
          str += ";";
        }
      });
      return str;
    },
  },
};
</script>

<style lang="scss" scoped>
// @import '~styles/mixins.scss';
// @import '~styles/variables.scss';
.upload-file-box {
}
</style>
